package com.yogee.topseller.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.GongsiDetailActivity;
import com.yogee.topseller.activity.HyqxActivity;
import com.yogee.topseller.activity.HyqxActivity1;
import com.yogee.topseller.activity.PayActivity;
import com.yogee.topseller.activity.ZhoubianActivity;
import com.yogee.topseller.bean.HuiyuanModel;
import com.yogee.topseller.bean.JigouBean;
import com.yogee.topseller.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import z.collapsedtextviewlibrary.CollapsedTextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @auathor ${XiaoJianghong}
 * @date 2017/6/26.
 */

public class JigouAdapter extends RecyclerView.Adapter<JigouAdapter.ItemHolder> {

    private Activity context;
    private List<JigouBean.Company> beans = new ArrayList<>();
    private int mSelectedPos = 0;//实现单选  方法二，变量保存当前选中的position

    private RecyclerView mRv;

    public JigouAdapter(Activity context,RecyclerView mRv) {
        this.context = context;
        this.mRv = mRv;

    }

    public void addData(List<JigouBean.Company> beans) {
        this.beans = beans;
        if(beans!=null&&beans.size()>0){
            JigouBean.Company company = beans.get(0);
            company.setType(((ZhoubianActivity)context).getType());
            company.setType(((ZhoubianActivity)context).getProId());
            ((ZhoubianActivity)context).setCurrentPosInfo(company);
            mSelectedPos= 0;
        }else{
            ((ZhoubianActivity)context).setCurrentPosInfo(null);
            mSelectedPos=-1;
        }
        notifyDataSetChanged();
    }

    @Override
    public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_jigou, parent, false);
        return new ItemHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemHolder holder, final int position) {
        if(position==mSelectedPos){
            holder.img_select.setVisibility(View.VISIBLE);
            holder.tv_name.setTextColor(context.getResources().getColor(R.color.select_color));
        }else{
            holder.img_select.setVisibility(View.INVISIBLE);
            holder.tv_name.setTextColor(context.getResources().getColor(R.color.color1));
        }
        if(position==0)
            holder.view_line.setVisibility(View.GONE);
        else
            holder.view_line.setVisibility(View.VISIBLE);

        holder.tv_name.setText(beans.get(position).getName());
        final TextView tv = holder.tv_detail;
        final TextView tv_btn = holder.tv_btn;
        if (TextUtils.isEmpty(beans.get(position).getDetails())){
            tv.setText("暂无详细信息");
            tv_btn.setVisibility(View.GONE);
        }else{
            tv_btn.setVisibility(View.VISIBLE);
            tv.setText(Html.fromHtml(beans.get(position).getDetails()));

//            final boolean b = tv.isNeedCollapse();
//            if (!b) //如果不需要折叠,button就隐藏
//                tv_btn.setVisibility(View.GONE);
        }
        tv.post(new Runnable() {
            @Override
            public void run() {
                //获取textView的行数
                int txtPart = tv.getLineCount();
                if(txtPart>2){
                    tv.setMaxLines(2);
                    tv_btn.setText("展开");
                    tv_btn.setVisibility(View.VISIBLE);
                }else{
                    tv_btn.setVisibility(View.GONE);
                }
            }
        });
        tv_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(tv_btn.getText().toString().equals("展开")){
                    tv.setMaxLines(Integer.MAX_VALUE);  //Integer.MAX_VALUE
                    tv_btn.setText("收起");
                }else{
                    tv.setMaxLines(2);
                    tv_btn.setText("展开");
                }
//                boolean collapsed = tv.isCollapsed;
//                if (collapsed) {//如果折叠了,就展开
//                    tv.collapse();
//                    tv_btn.setText("收起");
//                } else {//如果没折叠,就折叠
//                    tv.collapse();
//                    tv_btn.setText("展开");
//                }
            }
        });


        holder.tv_goto_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                context.startActivity(new Intent().setClass(context, HyqxActivity1.class).putExtra("fxjg",beans.get(position).getName()));
//                getId(beans.get(position).getName());
                ((ZhoubianActivity)context).getId(beans.get(position).getName());
            }
        });
        holder.tv_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if(position!=mSelectedPos) {
//                    int old_pos = mSelectedPos;
//                    mSelectedPos = position;
//                    notifyItemChanged(old_pos);
//                    notifyItemChanged(mSelectedPos);
//                }
                if(position!=mSelectedPos){
                    JigouAdapter.ItemHolder itemHolder = (ItemHolder) mRv.findViewHolderForLayoutPosition(mSelectedPos);
                    if(itemHolder!=null){
                        itemHolder.img_select.setVisibility(View.INVISIBLE);
                        itemHolder.tv_name.setTextColor(context.getResources().getColor(R.color.color1));
                    }else{
                        notifyItemChanged(mSelectedPos);
                    }
                    mSelectedPos = position;
                    notifyItemChanged(mSelectedPos);
                    JigouBean.Company company = beans.get(mSelectedPos);
                    company.setType(((ZhoubianActivity)context).getType());
                    company.setType(((ZhoubianActivity)context).getProId());
                    ((ZhoubianActivity)context).setCurrentPosInfo(company);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return beans == null ? 0 : beans.size();
    }

    class ItemHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.view_line)
        View view_line;
        @BindView(R.id.tv_name)
        TextView tv_name;
//        @BindView(R.id.tv_detail)
//        CollapsedTextView tv_detail;
        @BindView(R.id.tv_detail)
        TextView tv_detail;
        @BindView(R.id.img_select)
        ImageView img_select;
        @BindView(R.id.tv_goto_detail)
        TextView tv_goto_detail;
        @BindView(R.id.tv_btn)
        TextView tv_btn;


        public ItemHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    private void getId(String name) {
        if (!NetUtil.isNetworkAvailable()) {
            ToastUtils.showToast(context, "网络中断了，请重新链接网络。");
            return;
        }
        if(((ZhoubianActivity)context).pd!=null){
            ((ZhoubianActivity)context).pd.show();
        }
        //组装调取银行卡验证api的数据
        JSONObject object = new JSONObject();
        try {
            object.put("name", name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //网络调取api
//        OkHttpClient okHttpClient = new OkHttpClient();

        OkHttpClient okHttpClient =
                new OkHttpClient.Builder()
                        .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(60,TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(60,TimeUnit.SECONDS)//设置连接超时时间
                        .build();
        Request.Builder builder = new Request.Builder();

        Request request = builder.get()
                .url("http://open.api.tianyancha.com/services/v4/open/baseinfo?name="+name)  //fxjg
                .addHeader("Authorization", "09d5ca00-9913-4490-bba2-eedf81599fbf")
//                .addHeader("Content-Type", "application/json; charset=UTF-8")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, final IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        if(((ZhoubianActivity)context).pd!=null){
                            ((ZhoubianActivity)context).pd.dismiss();
                        }
//                        new Handler().post(runnable);//在子线程中直接去new 一个handler
                        ToastUtils.showToast(context,"无数据");
                        Looper.loop();
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                new Thread(new Runnable(){
                    @Override
                    public void run() {

                        try {

                            Gson gson = new Gson();
                            String result = response.body().string().replace("\n","");
                            LogUtils.e("success",result);
                            JSONObject jsonObject = new JSONObject(result);
                            int error_code = jsonObject.getInt("error_code");
                            if(error_code!=0){
                                if(((ZhoubianActivity)context).pd!=null){
                                    ((ZhoubianActivity)context).pd.dismiss();
                                }
                                Looper.prepare();
//                                new Handler().post(runnable);//在子线程中直接去new 一个handler
                                ToastUtils.showToast(context,"无数据");
                                Looper.loop();
                            }else{
                                if(((ZhoubianActivity)context).pd!=null){
                                    ((ZhoubianActivity)context).pd.dismiss();
                                }
                                long id = jsonObject.getJSONObject("result").getLong("id");
                                LogUtils.e("id","id:"+id);
                                context.startActivity(new Intent().setClass(context, HyqxActivity1.class).putExtra("fxjg",id));
                            }
                        } catch (Exception e) {
                            if(((ZhoubianActivity)context).pd!=null){
                                ((ZhoubianActivity)context).pd.dismiss();
                            }
                            LogUtils.e("error","错误信息:"+e.toString());
                            Looper.prepare();
//                            new Handler().post(runnable);//在子线程中直接去new 一个handler
                            ToastUtils.showToast(context,"无数据");
                            Looper.loop();
                        }
                    }
                }).start();

            }
        });
    }

    final Runnable runnable = new Runnable() {

        @Override
        public void run() {
            ToastUtils.showToast(context,"无数据");
        }
    };

}